// pages/toplist/toplist.js
var MusicRank = require('../../api/rank');
var app = getApp();
var Song = require('../../api/song')
var util = require("../../utils/util.js");

Page({
  data: {
    topinfo: {},
    id: 0,
    bgImage:'',
    songlist:[],
    songname:'',
    albumname:'',
    singerName: '',
    scrollTop: 100
  },

  //点击随机播放
  randomPlay(){
    var list = this._normalizeSongs(this.data.songlist)
    app.globalData.playMode = 2
    app.globalData.sequenceList = list
    app.globalData.playList = util.shuffle(app.globalData.sequenceList)
    app.globalData.playing = true
    app.globalData.currentIndex = 0

    wx: wx.navigateTo({
      url: '../play/play'
    })
  },
  //事件处理函数
  selectSong(e){
    var dataSet = e.currentTarget.dataset;
    var index = dataSet.index;
    var list = this._normalizeSongs(this.data.songlist);

    app.globalData.sequenceList = list;
    app.globalData.playList = list;
    app.globalData.index = index;
    app.globalData.currentIndex = index;
    app.globalData.playing = true
    wx:wx.navigateTo({
      url: '../play/play'
    })
    console.log(app.globalData.playMode)
    //如果是随机模式
    if(app.globalData.playMode == 2){
      app.globalData.playList = util.shuffle(app.globalData.sequenceList)
      var currentSong = app.globalData.sequenceList[app.globalData.currentIndex]
      var index = app.globalData.playList.findIndex((song) => {
        return song.id === currentSong.id
      })
      app.globalData.currentIndex = index;
    }
  },
  _normalizeSongs(list) {
    let ret = []
    list.forEach((musicData) => {
      if (musicData.data.songid && musicData.data.albummid) {
        ret.push(Song.createSong(musicData.data))
      }
    })
    return ret
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var self = this;
    var id = app.globalData.topList.id;
    var bgImage = app.globalData.topList.picUrl;

    this.setData({
      id: id,
      bgImage: bgImage
    });
    MusicRank.getMusicList(id,this.getTopListCallback)
  },
  getTopListCallback:function(data){
    var self = this;
    // for(var i=0;i<data.songlist.length;i++){
    //   var dd = data.songlist[i].data;
    //   this.setData({
    //     songname: dd.songname,
    //     albumname: dd.albumname,
    //     singerName: dd.singer[0].name
    //   })
    // }
    this.setData({
      topinfo:data.topinfo,
      songlist: data.songlist
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})